package cn.mazd.imagestorage.util;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class UploadUtil {

    @Value("${fingerling.upload.image.base.path}")
    private String uploadPath;

    @Value("${fingerling.upload.image.context.path}")
    private String contextPath;

    @Value("${fingerling.upload.image.online.path}")
    private String onlinePath;

    @Value("${upload.image.valid.suffixes}")
    private String validSuffix;


    public String upload(MultipartFile file) throws IOException {

        //获取文件名称；
        String name = file.getOriginalFilename();

        //获取当前时间作为最终存储文件的上级目录；
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String today = format.format(new Date());

        //保存的文件名：UUID+文件后缀；
        String fileName = UUID.randomUUID().toString()+ getFileSuffix(name);
        //文件类型校验；
        String type = getFileSuffix(name);
        log.info("文件类型：{}",type);
        if (!validSuffix.contains(type)) {
            log.error("UploadFile failed for suffix error;error sufiix:" + type);
            throw new IOException("M2-000001");
        }

        //文件最终上传地址；
        String uploadFolder = uploadPath + File.separator + today;

        //上传文件；
        File dir = new File(uploadFolder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String targetUploadPath = dir + File.separator + fileName;
        String targetContextPath = contextPath + File.separator + today + File.separator + fileName;
        try {
            FileUtils.writeByteArrayToFile(new File(targetUploadPath), file.getBytes());
        } catch (IOException e) {
            log.error("UploadFile failed", e);
            throw new IOException("M2-000002");
        }
        //返回文件存储位置；
        return onlinePath+targetContextPath;
    }


    public  MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            return new Base64DecodeMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String getFileSuffix(String name) {
        return name.substring(name.lastIndexOf("."), name.length());
    }

}
